package com.zjitc.controller;

import com.zjitc.common.ServerResponse;
import com.zjitc.model.User;
import com.zjitc.service.UserService;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/18 16:06
 * @description:
 */
@Controller
@RequestMapping("/user")
public class UserController {
  @Autowired
  private UserService userService;
  @RequestMapping("/index")
  public String index() {
    return "index";
  }

//登陆
  @RequestMapping("/login")
  public String login(
      @RequestParam(name = "username", required = false) String username,
      @RequestParam(name = "password", required = false) String password,
      HttpSession session, HttpServletResponse res
  ) throws IOException {
    if (username == null && password == null) {
      return "login";
    }
    ServerResponse<User> response = userService.login(username, password);
    if (response.success()) {
      session.setAttribute("user", response.getData());
      return "index";
    }
    session.setAttribute("msg", response.getMsg());
    return "login";
  }

  //注册
  @RequestMapping("/register")
  public String register(User user, HttpSession session) {
    if (user.getUsername()==null){
      return "register";
    }
    ServerResponse<User> response = userService.register(user);
    if (response.getStatus() == 1) {
      session.setAttribute("msgs", "用户名已经被注册");
      return "register";
    } else {
      return "login";
    }
  }
  //退出
  @RequestMapping("/logout")
  public String logout(HttpSession session){
    session.removeAttribute("user");
    return "index";
  }
  //修改
  @RequestMapping("/update")
  public String updateinformation(User user, HttpSession session) {
    User sessionUser = (User) session.getAttribute("user");
    ServerResponse<User> response = userService.updateInformation(user);
    if(user==null){
      return "login";
    }
    if(response.getStatus()==1){
      session.setAttribute("","更新失败");
      return "xiugai";
    }else {
      session.removeAttribute("");
      return "index";
    }

  }
  //修改
  @RequestMapping("/updateinformation")
  public String updateinformation(HttpSession session){
    User user=(User)session.getAttribute("user");
    ServerResponse<User> userServerResponse = new ServerResponse<>(1, user);
    if(user==null){
      return "login";
    }
    return "xiugai";
  }

}
